// $codepro.audit.disable closeInFinally, closeWhereCreated
/** Persistence Class */
package edu.gatech.utilities;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;


import edu.gatech.userclasses.User;


/**
 * @author Dan Holdridge
 * @version 2.0
 */
public class Persistence implements Serializable{
	
	/**
	 * Needed for Serializable objects
	 */
	private static final long serialVersionUID = 9125433008505906290L;

	/**
	 * The name of the file the Serialized objects are being written to.
	 */
	private static final String FILENAME = "persist/persistFile";

	/** User List */
	private static Collection<User> UserList = null;

	/**
	 * Saves the list of users to a file
	 */
	public static void save() {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(FILENAME));
			out.writeObject(UserList);
			out.close();
	//		Server.put();
		} catch (FileNotFoundException e) {
			System.err.println("Cannot open file " + FILENAME);
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Save failed");
			e.printStackTrace();
		}
	}

	/** 
	 * Loads the list of users to a file 
	 */
	@SuppressWarnings("unchecked")
	public static void load() {
		try {
	//		Server.get();
			final ObjectInputStream in = new ObjectInputStream
			(new FileInputStream(FILENAME));
			UserList = (Collection<User>) in.readObject();
			in.close();
		} catch (FileNotFoundException e) {
			System.err.println("Could not find file " + FILENAME);
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Other input failure during object read");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println("Failed to find class type on object read");
			e.printStackTrace();
		}
	}

	/** Saves then loads, as a way to "refresh" the list
	 */
	public static void refresh(){
		save();
		load();
	}

	/** @return String */
	public String toString(){
		return "Saved";
	}

	/** @return the userList */
	public static Collection<User> getUserList() {
		return UserList;
	}

	/** @param userList the userList to set */
	public static void setUserList(Collection<User> userList) {
		Persistence.UserList = userList;
	}

	/** @return the serialversionuid */
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}
